package com.leyou.filter;

import com.leyou.auth.utils.JwtUtils;
import com.leyou.common.utils.CookieUtils;
import com.leyou.config.FilterProperties;
import com.leyou.config.JwtProperties;
import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Component;
import sun.util.PreHashedMap;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

@Component
@EnableConfigurationProperties({JwtProperties.class,FilterProperties.class})
public class LoginFilter extends ZuulFilter {
    @Autowired
    private JwtProperties jwtProperties;
    @Autowired
    private FilterProperties filterProperties;

    @Override
    public String filterType() {
        return "pre";
    }

    @Override
    public int filterOrder() {
        return 1;
    }

    @Override//为true则拦截，false则不拦截
    public boolean shouldFilter() {

        //获取cookie中的token，利用工具类判断是否校验通过
        //利用父类中的上下文获取所需的request
        RequestContext currentContext = RequestContext.getCurrentContext();
        HttpServletRequest request = currentContext.getRequest();
        //获取当前url
        String requestURI = request.getRequestURI();

        //如果是白名单则不拦截
        List<String> allowPaths = filterProperties.getAllowPaths();
        for (String allowPath : allowPaths) {
            if(requestURI.startsWith(allowPath)){//获取的拦截路径以白名单开头则不拦截
                return false;
            }
        }

        return true;
    }

    @Override//拦截的具体逻辑
    public Object run() throws ZuulException {
        //获取cookie中的token，利用工具类判断是否校验通过
        //利用父类中的上下文获取所需的request
        RequestContext currentContext = RequestContext.getCurrentContext();
        HttpServletRequest request = currentContext.getRequest();
        //获取token
        String token = CookieUtils.getCookieValue(request, jwtProperties.getCookieName());
        try {

            //利用公钥解密，通过校验则放行，否则拦截,放行什么都不做
            JwtUtils.getInfoFromToken(token, jwtProperties.getPublicKey());

        } catch (Exception e) {
            e.printStackTrace();
            //异常就是没有token，没有权限401
            currentContext.setResponseStatusCode(401);
            currentContext.setSendZuulResponse(false);
        }
        return null;
    }
}
